<script setup lang="ts">
import { h, nextTick, reactive, ref, watch } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { HotTable } from '@handsontable/vue3'
import { Button, Divider, message } from 'ant-design-vue'
import Handsontable from 'handsontable'
import { registerAllModules } from 'handsontable/registry'

import { useVbenForm } from '#/adapter/form'
import { getUserBaseApi } from '#/api'
import { caclWareStockNum, createCutedOrder, cutedOrderAgainst, cutedOrderApproval, cutedOrderDel, getWarehouseDetail, goodsPurchaseEdit, updateCutedOrder } from '#/api/cutedOrder'

import product from '../../modules/product.vue'
import TotalSkuFunction from './Form.vue'

import 'handsontable/dist/handsontable.full.css'

registerAllModules()

const [productModal, productModalApi] = useVbenModal({
  connectedComponent: product,
  destroyOnClose: true,
})
const adminInfo = reactive({
  role_ids: [] as any,
})
const operate = ref('')
const inputDisabled: any = ref<boolean>(false)
const hotTableComponent = ref<any>(null)
const avgTableComponent = ref<any>(null)
const wareTableComponent = ref<any>(null)
const TableComponent = ref<any>(null)
const totalTableComponent = ref<any>(null)
const totalAvgTableComponent = ref<any>(null)

const showTable = ref(false)
const showStock = reactive({
  showData: false,
  avgData: ref([]),
  data: ref([]),
})
const highlight = reactive({
  row: undefined,
  col: undefined,
})
const changeStock = reactive({
  showData: false,
  data: ref([]),
})

const totalStock = reactive({
  showData: false,
  data: ref([]),
  avgData: ref([]),
})
const info = reactive({
  sku_total_data: [] as any,
  posted: 0,
  id: 0,
  // current_num: 0;
})
// 计算分仓
async function selWarehouse() {
  const form = await baseFormApi.getValues()
  if (!form.total_num) {
    message.error('请填写裁床总数')
    return
  }
  if (!form.goods_purchase_sn) {
    message.error('请选择采购单')
    return
  }
  const data = {
    not_cut_warehouse_ids: form.not_cut_warehouse_ids,
    goods_purchase_sn: form.goods_purchase_sn,
    goods_no: form.goods_no,
    diff_num: form.diff_num,
    total_num: form.total_num,
    order_type: form.order_type,
    total_sku: form.total_sku,
  }

  caclWareStockNum(data).then((res: any) => {
    if (res.data.code != 1) {
      message.error(res.data.msg)
      return
    }
    changeStock.data = res.data.data.stock_detail
    wareTableComponent.value.hotInstance?.loadData(changeStock.data)
    info.sku_total_data = changeStock.data[6]
    TableComponent.value.hotInstance.loadData(info.sku_total_data)
    showTable.value = true
    initCurrentNum()
  })
}
async function pushData(data: any) {
  modalApi.lock(true)
  await baseFormApi.setValues({ goods_purchase_sn: data.erp_purchaseid }, false)
  await baseFormApi.setValues({ product_sn: data.production_sn }, false)
  await baseFormApi.setValues({ info: `${data.follow_order.SupplyCode}/${data.follow_order.SupplyNa}(${data.goods_no})` }, false)
  await baseFormApi.setValues({ goods_no: data.goods_no }, false)
  await baseFormApi.setValues({ ori_total_num: data.plan_total_num }, false)
  const form = await baseFormApi.getValues();
  await baseFormApi.setValues({
    diff_num: Number(form.total_num - data.plan_total_num ),
  });
  getWarehouseDetail({ goods_no: data.goods_no, goods_purchase_sn: data.erp_purchaseid }).then((res: any) => {
    modalApi.unlock()
    showStock.data = res.data.data.stock_detail
    showStock.avgData = res.data.data.shop_avg_data
    showStock.showData = true
    showTable.value = true
    // 重新渲染表格
    nextTick(() => {
      hotTableComponent.value.hotInstance?.loadData(showStock.data)
      hotTableComponent.value.hotInstance?.updateSettings({ width: '100%' })
      avgTableComponent.value.hotInstance?.loadData(showStock.avgData)
    })
  })
}
const [BaseForm, baseFormApi] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  showDefaultActions: false,
  // wrapperClass: 'grid-cols-5',
  commonConfig: {
    // 在label后显示一个冒号
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  // handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: '',
      fieldName: '_divider',
      formItemClass: 'col-span-6',
      hideLabel: true,
    },
    {
      component: 'Input',
      disabled: true,
      componentProps: {
        placeholder: '自动生成',
      },
      fieldName: 'order_no',
      label: '裁床单号',
    },
    {
      component: 'DatePicker',
      defaultValue: undefined,
      fieldName: 'cuted_date',
      disabled: inputDisabled,
      label: '单据日期',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Select',
      fieldName: 'order_type',
      disabled: inputDisabled,
      label: '单据类型',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '实数单',
            value: 1,
          },
          {
            label: '尾数单',
            value: 2,
          },
        ],
      },
    },
    {
      component: 'Input',
      disabled: inputDisabled,
      componentProps: {
        readonly:true,
        placeholder: '请选择生产单',
        onClick: (value: any) => {
          productModalApi.open()
        },
      },
      fieldName: 'product_sn',
      formItemClass: 'col-span-2',
      label: '生产单',
    },
    {
      component: 'Input',
      disabled: inputDisabled,
      componentProps: {
        placeholder: '请选择加工厂',
      },
      fieldName: 'info',
      label: '信息',
    },
    {
      component: 'InputNumber',
      disabled: true,
      componentProps: {
        placeholder: '请填写裁床总数',
      },
      fieldName: 'ori_total_num',
      label: '原总数',
    },
    {
      component: 'InputNumber',
      disabled: inputDisabled,
      componentProps: {
        placeholder: '裁床总数',
        onChange: async (value) => {
          const data = await baseFormApi.getValues()
          if (data.ori_total_num !== undefined) {
            await baseFormApi.setValues({ diff_num: Number(value - data.ori_total_num) })
          }
        },
      },
      fieldName: 'total_num',
      label: '裁床总数',
    },
    {
      component: 'Input',
      disabled: true,
      componentProps: {
        placeholder: '差异数',
      },
      fieldName: 'diff_num',
      label: '差异数',
    },
    {
      component: 'Input',
      disabled: true,
      componentProps: {
        placeholder: '当前总数',
      },
      fieldName: 'current_num',
      label: '当前总数',
    },
    {
      component: 'Select',
      fieldName: 'not_cut_warehouse_ids',
      label: '不参与分仓',
      disabled: inputDisabled,
      formItemClass: 'col-span-2',
      suffix: () => h(Button, { onClick: selWarehouse }, () => '+计算分仓'),
      componentProps: {
        allowClear: true,
        filterOption: true,
        mode: 'multiple',
        options: [
          { label: '广州云仓', value: '38' },
          { label: '南昌云仓', value: '36' },
          { label: '长沙云仓', value: '40' },
          { label: '贵阳云仓', value: '39' },
          { label: '武汉云仓', value: '37' },
          { label: '西安云仓', value: '66' },
        ],
      },
    },
    {
      component: 'Input',
      disabled: inputDisabled,
      componentProps: {
        placeholder: '备注',
      },
      formItemClass: 'col-span-2',
      fieldName: 'remark',
      label: '备注',
    },
  ],
  wrapperClass: 'grid-cols-6',
})

const hotSettings = {
  contextMenu: {
    // 单元格右击展示菜单
    items: {
      separator: Handsontable.plugins.ContextMenu.SEPARATOR,
    },
  },
  readOnly: true,
  afterChange(change, source) {
    if (source == 'loadData') {}
  },
  cells(row, col, prop) {
    const cellProperties = {}
    cellProperties.renderer = 'negativeValueRenderer'
    return cellProperties
  },
  fillHandle: 'vertical', // 是否开启拖拽复制操作(true,false,'horizontal'水平复制,'vertical'垂直复制)
  width: '100%',
  height: 250,
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  colHeaders: [
    '上<br>柜<br>数<br>',
    '仓库',

    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42',
    '合计',
  ],
  copyable: true, // 允许键盘复制
  copyPaste: true, // 复制粘贴
  manualColumnResize: true,
  columns: [
    { data: 'shop_num', width: 40 },
    { data: 'warehouse', width: 70 },

    { data: 'first', width: 40 },
    { data: 'second', width: 40 },
    { data: 'third', width: 40 },
    { data: 'fourth', width: 40 },
    { data: 'fifth', width: 40 },
    { data: 'sixth', width: 40 },
    { data: 'seventh', width: 40 },
    { data: 'eighth', width: 40 },
    { data: 'ninth', width: 40 },
    { data: 'tenth', width: 40 },
    { data: 'eleven', width: 40 },
    { data: 'twelve', width: 40 },
    { data: 'total', width: 60 },
  ],
}
const negativeValueRenderer = (instance, td, row, col, prop, value, cellProperties) => {
  td.innerHTML = value == 0 || value == '' || value == null ? '' : value
}

const negativeValueRenderer2 = (instance, td, row, col, prop, value, cellProperties) => {
  if (row == highlight.row && col == highlight.col) {
    td.className = 'custom-cell'
  }
  td.innerHTML = value == 0 || value == '' || value == null ? '' : value
}

const initCurrentNum = () => {
  let total_num = 0
  if (changeStock.data == undefined) {
    return
  }
  if (showStock.data == undefined) {
    return
  }
  if (showStock.avgData[0] == undefined) {
    return
  }
  let total_avg_shop_num: number | string = 0
  let avg_total: number | string = 0
  const change_data_total = []
  const total_avg_data = []
  fields.forEach((r, i) => {
    change_data_total[r.data] = 0
    total_avg_data[r.data] = 0
  })
  const max_index = 6
  changeStock.data.forEach((row, index) => {
    if (row.warehouse !== '合计') {
      fields.forEach((r, i) => {
        total_num = total_num + Number.parseInt(row[r.data] == '' ? 0 : row[r.data])
        change_data_total[r.data] = change_data_total[r.data] + Number.parseInt(row[r.data] == '' ? 0 : row[r.data])
      })
      fields.forEach((r, i) => {
        changeStock.data[6][r.data] = change_data_total[r.data]
      })
    }
    changeStock.data[index].total =
      Number.parseInt(row.first) +
      Number.parseInt(row.second) +
      Number.parseInt(row.third) +
      Number.parseInt(row.fourth) +
      Number.parseInt(row.fifth) +
      Number.parseInt(row.sixth) +
      Number.parseInt(row.seventh) +
      Number.parseInt(row.eighth) +
      Number.parseInt(row.ninth) +
      Number.parseInt(row.tenth) +
      Number.parseInt(row.eleven) +
      Number.parseInt(row.twelve)
    row.total = changeStock.data[index].total
    totalStock.data[index].shop_num = showStock.data[index].shop_num
    totalStock.data[index].total = avg_total = Number.parseInt(row.total == '' ? 0 : row.total) + Number.parseInt(showStock.data[index].total == '' ? 0 : showStock.data[index].total)
    fields.forEach((r, i) => {
      totalStock.data[index][r.data] = Number.parseInt(row[r.data] == '' ? 0 : row[r.data]) + Number.parseInt(showStock.data[index][r.data] == '' ? 0 : showStock.data[index][r.data])
    })
    const shop_num = Math.max(showStock.data[index].shop_num, 0)
    if (index < max_index) {
      totalStock.avgData[index].shop_num = shop_num
      fields.forEach((r, i) => {
        totalStock.avgData[index][r.data] = shop_num <= 0 ? 0 : (totalStock.data[index][r.data] / shop_num).toFixed(1)
      })
      totalStock.avgData[index].total = shop_num > 0 ? (totalStock.data[index].total / shop_num).toFixed(1) : 0
    } else {
      total_avg_shop_num = total_avg_shop_num + Number.parseInt(shop_num)
      fields.forEach((r, i) => {
        total_avg_data[r.data] = total_avg_shop_num <= 0 ? 0 : (totalStock.data[index][r.data] / total_avg_shop_num).toFixed(1)
      })
      totalStock.avgData[max_index].shop_num = total_avg_shop_num
      fields.forEach((r, i) => {
        totalStock.avgData[max_index][r.data] = total_avg_data[r.data]
      })
      const avgData_total = totalStock.data[index].total
      totalStock.avgData[max_index].total = total_avg_shop_num > 0 ? (avgData_total / showStock.data[max_index].shop_num).toFixed(1) : 0
    }
  })
  // info.current_num = total_num

  baseFormApi.setValues({ current_num: total_num }, false)
}
const wareSettings = {
  contextMenu: {
    // 单元格右击展示菜单
    items: {
      separator: Handsontable.plugins.ContextMenu.SEPARATOR,
    },
  },
  afterChange(change, source) {
    if (source == 'loadData') {
      return
    }
    initCurrentNum()
  },
  cells(row, col, prop) {
    const cellProperties = {}
    cellProperties.renderer = 'negativeValueRenderer'
    return cellProperties
  },
  afterSelection(row, col, row2, col2) {
    highlight.row = row
    highlight.col = col
    // nextTick(() => {
    totalAvgTableComponent.value?.hotInstance?.loadData(totalStock.avgData)
    totalTableComponent.value?.hotInstance?.loadData(totalStock.data)
    // })
  },
  fillHandle: 'vertical', // 是否开启拖拽复制操作(true,false,'horizontal'水平复制,'vertical'垂直复制)
  width: '100%',
  height: 250,
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  colHeaders: [
    '上<br>柜<br>数<br>',
    '仓库',

    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42<br>均码',
    '合计',
  ],
  copyable: true, // 允许键盘复制
  copyPaste: true, // 复制粘贴
  colWidths: 130,
  manualColumnResize: true,
  columns: [
    { data: 'shop_num', width: 50, type: 'numeric' },
    { data: 'warehouse', width: 70 },

    { data: 'first', width: 40, type: 'numeric' },
    { data: 'second', width: 40, type: 'numeric' },
    { data: 'third', width: 40, type: 'numeric' },
    { data: 'fourth', width: 40, type: 'numeric' },
    { data: 'fifth', width: 40, type: 'numeric' },
    { data: 'sixth', width: 40, type: 'numeric' },
    { data: 'seventh', width: 40, type: 'numeric' },
    { data: 'eighth', width: 40, type: 'numeric' },
    { data: 'ninth', width: 40, type: 'numeric' },
    { data: 'tenth', width: 40, type: 'numeric' },
    { data: 'eleven', width: 40, type: 'numeric' },
    { data: 'twelve', width: 40, type: 'numeric' },
    { data: 'total', width: 60, type: 'numeric' },
  ],
}
const fields = [
  { data: 'first' },
  { data: 'second' },
  { data: 'third' },
  { data: 'fourth' },
  { data: 'fifth' },
  { data: 'sixth' },
  { data: 'seventh' },
  { data: 'eighth' },
  { data: 'ninth' },
  { data: 'tenth' },
  { data: 'eleven' },
  { data: 'twelve' },
]
const warehouseData = ['广州云仓', '南昌云仓', '长沙云仓', '武汉云仓', '贵阳云仓', '西安云仓']
const openFunction = () => {
  if (showStock.data == undefined || showStock.data.length <= 0) {
    showStock.data = []
    warehouseData.forEach((row, index) => {
      showStock.data.push({
        warehouse: row,
        shop_num: 0,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
      })
    })
  }

  if (changeStock.data == undefined || changeStock.data.length <= 0) {
    changeStock.data = []
    warehouseData.forEach((row, index) => {
      changeStock.data.push({
        warehouse: row,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
      })
    })
  }

  if (totalStock.data == undefined || totalStock.data.length <= 0) {
    warehouseData.forEach((row, index) => {
      totalStock.data.push({
        warehouse: row,
        shop_num: 0,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
        total: 0,
      })
      totalStock.avgData.push({
        warehouse: row,
        shop_num: 0,
        first: 0,
        second: 0,
        third: 0,
        fourth: 0,
        fifth: 0,
        sixth: 0,
        seventh: 0,
        eighth: 0,
        ninth: 0,
        tenth: 0,
        eleven: 0,
        twelve: 0,
        total: 0,
      })
    })
    totalStock.data.push({
      warehouse: '合计',
      shop_num: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    })
    totalStock.avgData.push({
      warehouse: '全国店均',
      shop_num: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    })
    showStock.data.push({
      warehouse: '合计',
      shop_num: 0,
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
      total: 0,
    })
    changeStock.data.push({
      warehouse: '合计',
      first: 0,
      second: 0,
      third: 0,
      fourth: 0,
      fifth: 0,
      sixth: 0,
      seventh: 0,
      eighth: 0,
      ninth: 0,
      tenth: 0,
      eleven: 0,
      twelve: 0,
    })
  }
  if (operate.value === 'add') {
    // baTable.form.items!.cuted_date = getDate()
    // baTable.form.items!.order_type = '1'
    // baTable.form.items!.goods = { goods_category: '', season: '', goods_name: '' }
    inputDisabled.value = false
    showTable.value = false
  }
  if (operate.value === 'edit') {
    inputDisabled.value = true
    showTable.value = true
  }
}
const totalSettings = {
  contextMenu: {
    // 单元格右击展示菜单
    items: {
      separator: Handsontable.plugins.ContextMenu.SEPARATOR,
    },
  },
  readOnly: true,
  afterChange(change, source) {
    if (source == 'loadData') {}
  },
  cells(row, col, prop) {
    const cellProperties = {}
    cellProperties.renderer = 'negativeValueRenderer2'
    return cellProperties
  },
  fillHandle: 'vertical', // 是否开启拖拽复制操作(true,false,'horizontal'水平复制,'vertical'垂直复制)
  width: '100%',
  height: 250,
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  colHeaders: [
    '上柜数',
    '仓库',

    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42',
    '合计',
  ],
  copyable: true, // 允许键盘复制
  copyPaste: true, // 复制粘贴
  colWidths: 130,
  manualColumnResize: true,
  columns: [
    { data: 'shop_num', width: 50 },
    { data: 'warehouse', width: 70 },

    { data: 'first', width: 40 },
    { data: 'second', width: 40 },
    { data: 'third', width: 40 },
    { data: 'fourth', width: 40 },
    { data: 'fifth', width: 40 },
    { data: 'sixth', width: 40 },
    { data: 'seventh', width: 40 },
    { data: 'eighth', width: 40 },
    { data: 'ninth', width: 40 },
    { data: 'tenth', width: 40 },
    { data: 'eleven', width: 40 },
    { data: 'twelve', width: 40 },
    { data: 'total', width: 60 },
  ],
}
const totalAvgSettings = {
  contextMenu: {
    // 单元格右击展示菜单
    items: {
      separator: Handsontable.plugins.ContextMenu.SEPARATOR,
    },
  },
  readOnly: true,
  afterChange(change, source) {
    if (source == 'loadData') {}
  },
  cells(row, col, prop) {
    const cellProperties = {}
    cellProperties.renderer = 'negativeValueRenderer2'
    return cellProperties
  },
  fillHandle: 'vertical', // 是否开启拖拽复制操作(true,false,'horizontal'水平复制,'vertical'垂直复制)
  width: '100%',
  height: 250,
  licenseKey: '2280d-dad74-843c8-51a09-b5218',
  colHeaders: [
    '上柜数',
    '仓库',

    '28<br>46<br>165<br>37<br>S',
    '29<br>48<br>170<br>38<br>M',
    '30<br>50<br>175<br>39<br>L',
    '31<br>52<br>180<br>40<br>XL',
    '32<br>54<br>185<br>41<br>2XL',
    '33<br>56<br>190<br>42<br>3XL',
    '34<br>58<br>195<br>43<br>4XL',
    '35<br><br><br><br>5XL',
    '36<br><br><br><br>6XL',
    '38<br><br><br><br>7XL',
    '40',
    '42',
    '店均',
  ],
  copyable: true, // 允许键盘复制
  copyPaste: true, // 复制粘贴
  colWidths: 130,
  manualColumnResize: true,
  columns: [
    { data: 'shop_num', width: 50, type: 'numeric' },
    { data: 'warehouse', width: 70, type: 'numeric' },

    { data: 'first', width: 40, type: 'numeric' },
    { data: 'second', width: 40, type: 'numeric' },
    { data: 'third', width: 40, type: 'numeric' },
    { data: 'fourth', width: 40, type: 'numeric' },
    { data: 'fifth', width: 40, type: 'numeric' },
    { data: 'sixth', width: 40, type: 'numeric' },
    { data: 'seventh', width: 40, type: 'numeric' },
    { data: 'eighth', width: 40, type: 'numeric' },
    { data: 'ninth', width: 40, type: 'numeric' },
    { data: 'tenth', width: 40, type: 'numeric' },
    { data: 'eleven', width: 40, type: 'numeric' },
    { data: 'twelve', width: 40, type: 'numeric' },
    { data: 'total', width: 60, type: 'numeric' },
  ],
}
const sku_data = ref()
watch(
  () => changeStock.data,
  (newValue, oldValue) => {
    sku_data.value = newValue
    totalStock.showData = true
    initCurrentNum()
  }
)

watch(
  () => sku_data.value,
  (newValue, oldValue) => {
    if (newValue === undefined) {
      return
    }
    changeStock.data = newValue
    changeStock.showData = true
  },
  { deep: true }
)

async function save() {
  modalApi.lock(true)
  const form = await baseFormApi.getValues()
  const data = {
    ...form,
    total_stock: totalStock.data,
    sku_data: changeStock.data,
  }

  if (operate.value === 'add') {
    createCutedOrder(data).then((res) => {
      modalApi.unlock()
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
      } else {
        message.error(res.data.msg)
      }
    })
  } else {
    updateCutedOrder(data).then((res) => {
      modalApi.unlock()
      if (res.code !== 1) {
        message.error(res.data.msg)
        return
      }
      inputDisabled.value = true
    })
  }
}

async function saveWareNum() {
  modalApi.lock(true)
  const form = await baseFormApi.getValues()
  const data = {
    ...form,
    total_stock: totalStock.data,
    sku_data: changeStock.data,
    is_fc_save: true,
  }
  updateCutedOrder(data).then((res) => {
    modalApi.unlock()
    if (res.code !== 1) {
      message.error(res.data.msg)
      return
    }
    inputDisabled.value = true
  })
}

function handleDel() {
  modalApi.lock(true)
  const ids = [info.id]
  cutedOrderDel({ ids }).then((res: any) => {
    modalApi.unlock()
    if (res.data.code === 1) {
      modalApi.close()
      message.success(res.data.msg)
    } else {
      message.error(res.data.msg)
    }
  })
}
function handleApproval() {
  modalApi.lock(true)
  const ids = [info.id]
  cutedOrderApproval({ ids }).then((res: any) => {
    modalApi.unlock()
    if (res.data.code === 1) {
      message.success(res.data.msg)
      initData()
    } else {
      message.error(res.data.msg)
    }
  })
}

function handleAgainst() {
  modalApi.lock(true)
  const ids = [info.id]
  cutedOrderAgainst({ ids }).then((res: any) => {
    modalApi.unlock()
    if (res.data.code === 1) {
      message.success(res.data.msg)
      initData()
    } else {
      message.error(res.data.msg)
    }
  })
}

function changeToSave() {
  inputDisabled.value = false
}
function initData() {
  modalApi.lock(true)
  goodsPurchaseEdit({ id: info.id }).then((res: any) => {
    modalApi.unlock()
    if (res.data.code === 1) {
      inputDisabled.value = true
      showStock.showData = true
      totalStock.showData = true
      const row = res.data.data.row
      changeStock.data = row.sku_data
      wareTableComponent.value.hotInstance.loadData(changeStock.data)
      showStock.avgData = row.ori_data.shop_avg_data
      showStock.data = row.ori_data.stock_detail

      info.sku_total_data = row.sku_total_data
      info.posted = row.posted
      baseFormApi.setValues(row, false)
      if (hotTableComponent.value !== undefined && hotTableComponent.value !== null) {
        hotTableComponent.value.hotInstance.loadData(showStock.data)
        avgTableComponent.value.hotInstance.loadData(showStock.avgData)
      }
      initCurrentNum()
    } else {
      modalApi.close()
    }
  })
}

// 按尺码填写
const [TotalSkuFunctionModal, TotalSkuFunctionModalApi] = useVbenModal({
  connectedComponent: TotalSkuFunction,
  // destroyOnClose: true,
})
function showTotalSkuFunction() {
  TotalSkuFunctionModalApi.open()
}
async function saveTotalSku(data: any) {
  await baseFormApi.setValues({total_sku: data[0]}, false)
  await baseFormApi.setValues({total_num: data[0].total}, false)
  const form = await baseFormApi.getValues();
  await baseFormApi.setValues({ diff_num: Number(data[0].total - form.ori_total_num) })
}
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  fullscreen: true,
  appendToMain: true,
  showCancelButton: false,
  showConfirmButton: false,
  onCancel() {
    modalApi.close()
  },
  async onConfirm() {},
  onOpenChange: async (isOpen: boolean) => {
    if (!isOpen) return
    const { rowData, view } = modalApi.getData<Record<string, any>>()
    Handsontable.renderers.registerRenderer('negativeValueRenderer', negativeValueRenderer)
    Handsontable.renderers.registerRenderer('negativeValueRenderer2', negativeValueRenderer2)
    const data = await getUserBaseApi()
    adminInfo.role_ids = data.adminInfo.role_ids
    if (view === 'add') {
      inputDisabled.value = true
      const from = [
        {
          component: '',
          fieldName: 'butShowTotal',
        },
      ]
      baseFormApi.setState((prev) => {
        return {
          schema: [...(prev?.schema ?? []), ...from],
        }
      })
    } else {
      const from = [
        {
          component: 'Input',
          disabled: true,
          componentProps: {
            placeholder: '季节',
          },
          fieldName: 'goods.season',
          label: '季节',
        },
        {
          component: 'Input',
          disabled: inputDisabled,
          componentProps: {
            placeholder: '品名',
          },
          fieldName: 'goods.goods_name',
          label: '品名',
        },

        {
          component: '',
          fieldName: 'butShowTotal',
        },
      ]
      baseFormApi.setState((prev) => {
        return {
          schema: [...(prev?.schema ?? []), ...from],
        }
      })
      info.id = rowData.id
      initData()
    }
    operate.value = view
    openFunction()
  },
})
</script>

<template>
  <Modal title="生产裁床单">
    <TotalSkuFunctionModal @push-data="saveTotalSku" />
    <productModal @push-data="pushData" />
    <BaseForm>
      <template #_divider>
        <Divider orientation="left">基础信息</Divider>
      </template>
      <template #butShowTotal>
        <Button type="primary" @click="showTotalSkuFunction()" :disabled="inputDisabled">按尺码填写</Button>
      </template>
    </BaseForm>
    <div class="" v-show="showTable">
      <div style="width: 100%; overflow: hidden">
        <div v-show="showStock.showData" style="float: left; width: 50%">
          <strong>原分仓:</strong>
          <HotTable v-if="showStock.showData" ref="hotTableComponent" :data="showStock.data" :settings="hotSettings" />
        </div>
        <div v-if="showStock.showData && !adminInfo.role_ids.includes(6)" style="float: right; width: 50%">
          <strong>库存:</strong>
          <HotTable v-show="showStock.showData" ref="avgTableComponent" :data="showStock.avgData" :settings="hotSettings" />
        </div>
      </div>
      <div style="width: 100%; overflow: hidden">
        <div v-show="showStock.showData" style="float: left; width: 50%">
          <strong v-show="changeStock.showData">调整明细:</strong>
          <HotTable v-if="changeStock.showData" ref="wareTableComponent" :data="changeStock.data" :settings="wareSettings" />
        </div>
        <div v-show="operate === 'edit'" style="float: right; width: 50%">
          <strong>调整总量:</strong>
          <HotTable ref="TableComponent" :data="info.sku_total_data" :settings="wareSettings" />
        </div>
      </div>
      <div style="width: 100%; overflow: hidden">
        <div v-show="changeStock.showData" style="float: left; width: 50%">
          <h2>调整结果:</h2>
          <HotTable v-show="changeStock.showData" ref="totalTableComponent" :data="totalStock.data" :settings="totalSettings" />
        </div>
        <div v-show="changeStock.showData && !adminInfo.role_ids.includes(6)" style="float: right; width: 50%">
          <h2>店均:</h2>
          <HotTable v-if="changeStock.showData" ref="totalAvgTableComponent" :data="totalStock.avgData" :settings="totalAvgSettings" />
        </div>
      </div>
    </div>
    <template #prepend-footer>
      <Button @click="modalApi.close()">取消</Button>
      <!-- 保存按钮：编辑模式下inputDisabled为false时显示，新增模式下始终显示 -->
      <Button type="primary" @click="save()" v-if="(!inputDisabled && operate === 'edit') || operate === 'add'">保存</Button>
      <template v-if="operate === 'edit' && info.posted === 0">
        <!-- 修改按钮：编辑模式下inputDisabled为true时显示 -->
        <Button type="primary" v-if="inputDisabled" @click="changeToSave()">修改</Button>
        <Button type="primary" @click="handleApproval()">审核</Button>
        <Button type="primary" danger @click="handleDel()">删除</Button>
      </template>
      <template v-if="operate === 'edit' && info.posted > 0">
        <Button type="primary" @click="handleAgainst()" danger>反审</Button>
        <Button type="primary" @click="saveWareNum()">分仓保存</Button>
      </template>
    </template>
  </Modal>
</template>

<style scoped></style>
